﻿using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Hicap.AuthorizationServer.Core.Notify;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Hicap.AuthorizationServer.Core.Domains.Sys.Notification
{
    public class NotificationManager : AuthorizationServerDomainServiceBase, INotificationManager
    {
        private readonly IRepository<Models.Sys.Notification, int> _notificationRepository;
        private readonly IocManager _iocResolver;

        public NotificationManager(IRepository<Models.Sys.Notification, int> notificationRepository, IocManager iocResolver)
        {
            _notificationRepository = notificationRepository;
            _iocResolver = iocResolver;
        }

        [UnitOfWork]
        public void FinishedMessage(List<int> idList)
        {
            idList.ForEach(async x => await _notificationRepository.DeleteAsync(x)
                );
        }

        [UnitOfWork]
        public Task<List<Models.Sys.Notification>> ReadMessage(string type)
        {
            return Task.Run(() =>
           {
               return _notificationRepository.GetAll().Where(x => x.Type.Equals(type)).ToList();
           });
        }

        [UnitOfWork]
        public async Task Echo(string type, dynamic data)
        {
            Models.Sys.Notification entity = new Models.Sys.Notification()
            {
                @Type = type,
                MessageContent = JsonConvert.SerializeObject(data)
            };

            int messageId = await _notificationRepository.InsertAndGetIdAsync(entity);

            await SendNotification(type, entity.MessageContent, messageId);
        }

        private async Task SendNotification(string type, string data, int messageId)
        {
            NotifyHub notify = _iocResolver.Resolve<NotifyHub>();
            await notify.SendToGroup(type, messageId, data);
        }
    }
}